package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;

import commons.World;

/**
 * 
 * Entry point for server. 
 * Makes new threads for each connection.
 *
 */
public class OMGPServer {

	public static final String SERVER_NAME = "Drexel";
	private static int MAX_CONNECTIONS = 5;
	private static int PORT = 4171;
	private ServerSocket listenSocket;
	private int connections = 0;
	private int clientId = 0;
	private HashMap<Integer, OMGPConnectionThread> connectionHM;
	private HashMap<Integer, World> games;


	public OMGPServer(){

		//PlayersRepository pa
		connectionHM = new HashMap<Integer, OMGPConnectionThread>();		

		games = new HashMap<Integer, World>();
		games.put(1, new World("Geoff's game"));
		games.put(2, new World("n00bs only"));
		games.put(3, new World("free 4 all!"));

		try {

			listenSocket = new ServerSocket(PORT);

		} 
		catch (IOException e) {
			System.out.println("Couldn't open socket on port " + PORT);
			System.exit(1);
		}

		while (connections < MAX_CONNECTIONS) {
			Socket socket;
			try {
				socket = listenSocket.accept();
				System.out.println("Server has connected a new client.");
				OMGPConnectionThread connection = 
					new OMGPConnectionThread(socket, clientId, games);
				clientId++;

				connectionHM.put(new Integer(clientId), connection);
				connection.start();

			} catch (IOException e) {
				System.out.println("There was a problem with the new socket thread!");
				e.printStackTrace();
				System.exit(1);
			}
		}
	}

	public void closeConnection(int clientId){

		OMGPConnectionThread oConnectionThread = connectionHM.get(new Integer(clientId));
		oConnectionThread.close();
		connections--;
	}



	public void closeAllConns(){
		Iterator<OMGPConnectionThread> it = connectionHM.values().iterator();

		while(it.hasNext()){
			OMGPConnectionThread oConnectionThread = (OMGPConnectionThread) it.next();
			oConnectionThread.close();		
		}
		connections = 0;
	}


	public static void main(String args[]) {

		new OMGPServer();

	}
}

